<!-- 正文开始 -->
<style>
    .model-form .layui-form-label {
        width: 100px;
    }
    .model-form .layui-input-block {
        margin-left: 130px;
    }
    .w-120 {
        width: 115px;
    }

    .w-500 {
        width: 500px !important;
    }

    .title-txt {
        padding: 0 0 20px 30px;
        font-weight: 600;
        font-size: 18px;
    }

    .conentStyle {
        padding: 10px;
        box-sizing: border-box;
    }

    .conentBg {
        padding: 20px;
        box-sizing: border-box;
        border-radius: 5px;
        background-color: #fff;
        min-height: 660px;
    }

    .borderNone {
        border: none;
    }

    .formBg {
        background-color: #F7F8FA;
        padding: 20px;
    }
    .layui-table-cell{
        height: auto;
    }
    .layui-table-cell img{
        width: 80px;
        height: 80px;
    }

    .import {
        opacity: 0;
        position: absolute;
        width: 69px;
        height: 38px;
        margin-left: -10px;
    }
</style>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">物料编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="productCode" class="layui-input" type="text" placeholder="请输入物料编号" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">物料名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请物料名称" autocomplete="off"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="productBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                            <!--<button id="fromLocalWarehouseBtnImport" class="layui-btn icon-btn color-reseda">
                                <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx"/>导入
                            </button>-->
                        </div>
                        <!--<div class="lay-btn-rt">
                            <button id="fromLocalWarehouseBtnTemplate" class="layui-btn icon-btn color-green">模板下载
                            </button>
                        </div>-->
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="productTable" lay-filter="productTable"></table>
        </div>
    </div>
</div>



<!-- 表格操作列 -->
<script type="text/html" id="productTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <!--<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="synsSku">同步到云端</a>-->
    <!--<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>-->
    {{# if(d.isDeleted==false){  }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="cancellationTableBarBtn">作废</a>
    {{# }else{ }}
    <a class="layui-btn layui-btn-xs" lay-event="openTableBarBtn">开启</a>
    {{# } }}
</script>

<!-- 编辑SKU表格操作列 -->
<script type="text/html" id="skuTableBar">
    <!--    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">冻结</a>-->
    {{# if(d.isShow==true){  }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="frozen">冻结</a>
    {{# }else{ }}
    <a class="layui-btn layui-btn-xs" lay-event="thaw">解冻</a>
    {{# } }}


</script>

<!-- 数据同步到平台SKU表格操作列 -->
<script type="text/html" id="synsSkuTableBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="settingSpec">设置平台规格</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="syns">同步到云端</a>
</script>


<!-- 添加/修改表单弹窗 -->
<script type="text/html" id="productForm">
    <form lay-filter="productForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <!--<div class="layui-form-item">
            <label class="layui-form-label">物料名称</label>
            <div class="layui-input-inline">
                <input name="name" class="layui-input" type="text" placeholder="请输入物料名称"/>
            </div>
        </div>-->
        <div class="layui-form-item">
            <label class="layui-form-label">物料系列编码</label>
            <div class="layui-input-inline">
                <input name="productCode" id="productCode_edit" class="layui-input" type="text" placeholder="请输入物料编码" autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">物料系列名称</label>
            <div class="layui-input-inline">
                <input name="name" class="layui-input" type="text" placeholder="请输入物料系列名称" autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">物料类型</label>
            <div class="layui-input-inline">
                <select lay-filter="productTypeId" id="productTypeId" name="productTypeId" lay-search lay-verify="required">
                    <option value="">请选择物料类型</option>
                </select>
            </div>
            <div class="layui-form-mid layui-word-aux">
                <a href="#/product/productType" class="layui-btn layui-btn-xs" ew-event="closeDialog">
                    <i class="layui-icon layui-icon-addition"></i>
                </a>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">物料分类</label>
            <input name="productCategoryId" value="" type="hidden">
            <div class="layui-input-inline" id="productCategoryId"></div>
            <div class="layui-form-mid layui-word-aux">
                <a href="#/product/productCategory" class="layui-btn layui-btn-xs" ew-event="closeDialog">
                    <i class="layui-icon layui-icon-addition"></i>
                </a>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">扩展分类</label>
            <div class="layui-input-inline mr0" id="productCategoryExt">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">计价方式</label>
            <div class="layui-input-inline mr0">
                <select name="pricingMethod">
                    <option value="piece">按件</option>
                    <option value="weight">按重量</option>
                </select>
            </div>
        </div>
        <!--
        <div class="layui-form-item">
            <label class="layui-form-label">对应平台系列</label>
            <div class="layui-input-inline mr0">
                <select id="idPlatform" name="idPlatform" lay-verify="required" required lay-search></select>
            </div>
        </div>
        -->
        <!-- <div class="layui-form-item">
             <label class="layui-form-label">商品属性</label>
             <div class="layui-input-block">
                 <div class="layui-input-inline mr0" id="productAttrHtml" name="productAttrHtml">

                 </div>
                 <div id="productAttrValueHtml" name="productAttrValueHtml">

                 </div>
             </div>
         </div>
         <div class="layui-form-item">
             <label class="layui-form-label">商品规格</label>
             <div class="layui-input-block">
                 <div class="layui-input-inline mr0" id="productSpecHtml" name="productSpecHtml">

                 </div>
                 <div id="productSpecValueHtml" name="productSpecValueHtml">

                 </div>
                 <div id="productSkuHtml" name="productSkuHtml">
                     <table class="layui-table" id="productSkuTable" name="productSkuTable"
                            lay-filter="productSkuTable"></table>
                 </div>
             </div>
         </div>-->


        <div class="layui-form-item">
            <label class="layui-form-label">系列图片</label>
            <div id="btnUpload14" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传图片</div>
            <div id="btnUpload14_path" style="margin-left: 260px;line-height: 40px;"></div>
            <input id="picture" name="picture" type="hidden"/>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="productFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- 设置企业规格表单弹窗 -->
<script type="text/html" id="settingSpecForm">
    <form lay-filter="settingSpecForm" class="layui-form model-form">
        <div class="layui-form-item">
            <label class="layui-form-label w-120">平台物料编码</label>
            <div class="layui-input-inline">
                <input name="synsPlatformSkuCode" id="synsPlatformSkuCode" class="layui-input" type="text" disabled/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label w-120">平台规格</label>
            <div class="layui-input-block">
                <div class="layui-input-inline mr0" id="platformSpec" name="platformSpec">

                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label w-120">平台规格值</label>
            <div class="layui-input-inline w-500">
                <label class="layui-form-label w-500" style="padding-left: 0;text-align: left;"
                       id="platformProductSpecValueName" name="platformProductSpecValueName"></label>
                <input type="hidden" name="platformProductSpecValueId" id="platformProductSpecValueId" value="">
                <input type="hidden" name="platformProductSpecId" id="platformProductSpecId" value="">
            </div>
        </div>
        <div class="layui-form-item text-right">
            <a class="layui-btn" lay-filter="platformSpecSkuSetting" id="platformSpecSkuSetting">提交</a>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin',
        'layedit', 'tableTreeDj', 'newTree', 'laydate', 'upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var layedit = layui.layedit;
        var upload = layui.upload;
        var tableTree = layui.tableTreeDj;
        var newTree = layui.newTree;
        var laydate = layui.laydate;
        var upload = layui.upload;
        //
        let localMap = new Map(), localSkuData = [];

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-query-box").find('select').val("");
            $(".lay-query-box").find('input').val("");
            var field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 渲染表格
        var insTb = table.render({
            elem: '#productTable',
            url: config.base + 'enterprise/product/admin/productSeriesWMS/list',
            page: true,
            where: {
                "dataSourceType": 0,
                "type": 0,
                categoryType: 'production'
            },
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'}
                , {
                    field: 'picture', sort: true, title: '图片',
                    templet:function (d) {
                        if(d.picture){
                            return '<img src="'+ d.picture +'"/>';
                        }
                        return '<img src="assets/images/default-icon.png" style="cursor: pointer"/>';
                    }
                }
                , {field: 'name', sort: true, title: '物料系列名称'}
                , {field: 'productCode', sort: true, title: '物料系列编码'}
                , {field: 'productTypeName', title: '物料类型'}
                , {field: 'productCategoryName', title: '物料分类'}
                , {field: 'createTime', sort: true, title: '创建时间'}
                , {field: 'isDeleted', title: '状态',templet:d=> d.isDeleted?'<span style="color: #ff0000">已作废</span>':'<span style="color: #00C573">已开启</span>'}
                , {field: 'creatorName', sort: true, title: '创建人'}
                , {align: 'center', toolbar: '#productTableBar', title: '操作', width: 300}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                // var menuButton = config.getMenuButton(location.hash);
                // if (menuButton.indexOf("搜索") == -1) {
                //     $('.layui-form.toolbar').remove();
                // }
                // if (menuButton.indexOf("修改") == -1) {
                //     $("[lay-event='edit']").remove();
                // }
                // if (menuButton.indexOf("删除") == -1) {
                //     $("[lay-event='del']").remove();
                // }
            }
        });

        // 工具条点击事件
        table.on('tool(productTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'synsSku') { // 同步SKU到平台
                doSynsSku(obj);
            }else if(obj.event === 'cancellationTableBarBtn'){
                cancellation(data);
            }else if(obj.event === 'openTableBarBtn'){
                openTable(data);
            }
        });

        //监听排序
        table.on('sort(productTable)', function (obj) {
            table.reload('productTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        //渲染下拉框
        form.render('select');

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            //数据来源:enterprise(0,企业);platform(1,平台)
            data.field.dataSourceType = 0;
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });


        /**
         * 加载地址HTML
         * @param data 下拉菜单数据
         * @param tips select 默认提示
         * @param htmltarget html要插入的位置
         * @param name  下拉框需要显示值的属性
         */
        function loadSelectHtml(data, tips, htmltarget, name) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                let isFinalCategory = '';
                if (data[i].isFinalCategory != undefined) {
                    isFinalCategory = `isFinal=` + data[i].isFinalCategory;
                }
                html += `<option value='${data[i].id}' ${isFinalCategory}>${data[i][name]}</option>`;
            }
            $("[name='" + htmltarget + "']").html(html);
            form.render();
        }

        /**
         * 加载地址HTML
         * @param data 下拉菜单数据
         * @param tips select 默认提示
         * @param htmltarget html要插入的位置
         * @param name  下拉框需要显示值的属性
         */
        function loadSelectHtmlByCode(data, tips, htmltarget, name) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                let isFinalCategory = '';
                if (data[i].isFinalCategory != undefined) {
                    isFinalCategory = `isFinal=` + data[i].isFinalCategory;
                }
                html += `<option value='${data[i].code}' ${isFinalCategory}>${data[i][name]}</option>`;
            }
            $("[name='" + htmltarget + "']").html(html);
            form.render();
        }

        function loadSpecValueHtml(data, name, productSpecId) {
            let html = "";
            if (!data || data == null) {
                layer.msg("物料类型规格值为空,请先前往配置物料规格值！", {icon: 2});
                return;
            }
            html += '<div style="margin-top: 20px" name="specValue' + name + '">';
            html += '<div class="layui-form-item">';
            html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + name + ':</label>';
            html += '<div class="layui-input-block">';

            for (let i = 0; i < data.length; i++) {
                html += '<input lay-filter="productSpecValue" type="checkbox" name  = "productSpecValue' + productSpecId + '"  value="' + data[i].id + '" lay-skin="primary" title="' + data[i].value + '">';
            }
            html += '</div>';
            html += '</div>';
            html += '</div>';
            //console.log(html);
            return html;
        }


        function createProductSpecValueSku(dbSkuMap) {


            //获取checkbox[name='like']的值
            $("[lay-id=productSkuTable] table").remove();
            var arrProductSpec = new Array();
            var arrProductSpecId = new Array();

            $("input:checkbox[name='productSpec']:checked").each(function (i) {
                arrProductSpec[i] = $(this).attr('title');
                arrProductSpecId[i] = $(this).val();
            });

            $("input:checkbox[lay-filter='productSpecValue']:checked").each(function (i) {
                productSpecValueByProductSpecValueIdsStr += $(this).val() + "_"
            });

            if (productSpecValueByProductSpecValueIdsStr.length > 0) {
                productSpecValueByProductSpecValueIdsStr = productSpecValueByProductSpecValueIdsStr.substring(0, productSpecValueByProductSpecValueIdsStr.length - 1);
                // 请求多规格参数
                admin.req('enterprise/product/admin/productSpecValue/getProductSpecValueByProductSpecValueIds', {productSpecValueIds: productSpecValueByProductSpecValueIdsStr}, res => {
                    if (res.code === 200) {
                        res.data.forEach(item => {
                            productSpecValueByProductSpecValueIds.set(item.id, item)
                        });
                    }
                }, 'get', false);
            }


            let headData = [];
            let skuData = [];
            headData.push({align: 'center', toolbar: '#skuTableBar', title: '操作', width: 70});
            headData.push({field: 'id', title: '序号', width: 85});
            headData.push({field: 'skuName', title: '物料名称'});
            headData.push({field: 'skuCode', title: '物料编码'});
            //headData.push({field: 'productPic', sort: true, title: 'SKU图片'})
            var skus = [];
            var celNames = [];
            var prefix = "CELL";
            for (var j = 0; j < arrProductSpecId.length; j++) {
                //var arrProductSpecValue = new Array();
                //var arrProductSpecValueId = new Array();

                // headData.push({field: prefix + "_" + j, sort: true, title: '' + arrProductSpec[j] + ''})
                celNames.push(prefix + "_" + j)

                var sku = [];
                $("input:checkbox[name='productSpecValue" + arrProductSpecId[j] + "']:checked").each(function (i) {
                    //arrProductSpecValue[i] = $(this).attr('title');
                    //arrProductSpecValueId[i] = $(this).val();
                    //物料规格和物料规格的值都需要传到后台数据库进行保存
                    sku.push($(this).attr('title') + ":" + arrProductSpecId[j] + ":" + $(this).val())
                });
                skus.push(sku);
            }
            var productSkus = createSku(skus);
            var newCreateSkuMap = new Map();
            if (productSkus) {
                productSkus.forEach(item => {
                    if (dbSkuMap) {
                        //60MM:2:5_白色:1:1
                        var array = item.split("_");
                        var temp = '';
                        for (let i = 0; i < array.length; i++) {
                            var array2 = array[i].split(":");
                            temp += array2[2] + "_";
                        }
                        temp = temp.substring(0, temp.length - 1);
                        var dbSku = dbSkuMap.get(temp);
                        if (dbSku) {
                            newCreateSkuMap.set(temp, dbSku);
                            localMap.set(temp, dbSku)
                        }
                    }
                })
            }

            headData.push({
                field: 'skuSpecValueNames',
                title: '规格码',
                templet: d => {
                    let arraySplicing = '';
                    let arraySplicingArray = [];
                    arraySplicingArray = $(d.skuName).eq(1).val().split('_');
                    for (let i = 0; i < arraySplicingArray.length; i++) {
                        if (productSpecValueByProductSpecValueIds.has(arraySplicingArray[i])) {
                            if (productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).specCode == '0') {
                                var specName = productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).value;
                                if (productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).specLocation == '0') {
                                    // beforeStr = productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).specHead;
                                    arraySplicing += productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).specHead + specName + "-";
                                } else if (productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).specLocation == '1') {
                                    // lastStr = productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).specHead;
                                    arraySplicing += specName + productSpecValueByProductSpecValueIds.get(arraySplicingArray[i]).specHead + "-";
                                }
                            }
                        }
                    }

                    return "<span name='skuSpecValueNamesSpan'>" + arraySplicing.substring(0, arraySplicing.length - 1) + "</span>"
                }
            });

            if (null == productSkus || "" == productSkus) {
                // layer.msg("物料规格值为空,请先前往配置物料规格值！", {icon: 2});
                return;
            }
            //var aa = eval("(" + productSkus + ")");
            //console.log(productSkus.length);
            var count = 1;

            for (var i = 0; i < productSkus.length; i++) {
                var celStr = {};
                var sukArray = productSkus[i].split("_");
                celStr["id"] = count;
                let skuSpec = '';
                let skuSpecValue = '';
                let skuSpecValueNames = '';
                for (var j = 0; j < sukArray.length; j++) {
                    var idArray = sukArray[j].split(":");
                    //['50MM:1:4', '白色:1:1']
                    // console.log(sukArray);
                    celStr[celNames[j]] = idArray[0];
                    skuSpec += idArray[1] + "_";
                    skuSpecValue += idArray[2] + "_";
                    skuSpecValueNames += idArray[0] + "-";
                }

                skuSpec = skuSpec.substring(0, skuSpec.length - 1);
                skuSpecValue = skuSpecValue.substring(0, skuSpecValue.length - 1);
                skuSpecValueNames = skuSpecValueNames.substring(0, skuSpecValueNames.length - 1);
                celStr["skuName"] = '<input type="hidden" name="skuSpec" value="' + skuSpec + '" ><input type="hidden" name="skuSpecValue" value="' + skuSpecValue + '" ><input type="text" name="skuName" id="skuName' + skuSpecValue + '" required  lay-verify="required" autocomplete="off" class="layui-input"><input type="hidden" name="skuSpecValueNames" value="' + skuSpecValueNames + '" >'
                celStr["skuCode"] = '<input type="text" name="skuCode" id="skuCode' + skuSpecValue + '"  lay-verify="required" autocomplete="off" class="layui-input">'
                //celStr["productPic"] = '<div id="btnUpload14" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传图片</div><div id="btnUpload14_path" style="margin-left: 260px;line-height: 40px;"></div>'
                celStr["spPrice"] = '<input type="text" name="spPrice" id="spPrice' + skuSpecValue + '"  lay-verify="required" autocomplete="off" class="layui-input">';
                celStr["marketPrice"] = '<input type="text" name="marketPrice" id="marketPrice' + skuSpecValue + '"  lay-verify="required" autocomplete="off" class="layui-input">';
                celStr["supplyPrice"] = '<input type="text" name="supplyPrice" id="supplyPrice' + skuSpecValue + '"  lay-verify="required" autocomplete="off" class="layui-input">';
                celStr["activityPrice"] = '<input type="text" name="activityPrice" id="activityPrice' + skuSpecValue + '"  lay-verify="required"  autocomplete="off" class="layui-input">';
                celStr["enterpriceCode"] = '<input type="text" name="enterpriceCode" id="enterpriceCode' + skuSpecValue + '"  lay-verify="required"  autocomplete="off" class="layui-input">';
                celStr["barcode"] = '<input type="text" name="barcode" id="barcode' + skuSpecValue + '"  lay-verify="required"  autocomplete="off" class="layui-input"><input type="hidden" name="skuId" id="skuId' + skuSpecValue + '" value="" >';
                celStr["oldSpecCode"] = '<input type="text" name="oldSpecCode" id="oldSpecCode' + skuSpecValue + '"  lay-verify="required"  autocomplete="off" class="layui-input" value="" >';
                skuData.push(celStr);
                if (localSkuData.length < skuData.length) {
                    localSkuData.push(celStr)
                }
                localSkuData.push(celStr);
                count++;
            }
            //headData.push({field: 'skuPic', sort: true, title: '商品图片'});


            headData.push({field: 'spPrice', title: '渠道价'});
            headData.push({field: 'marketPrice', title: '市场价'});
            headData.push({field: 'supplyPrice', title: '平台供货价'});
            headData.push({field: 'activityPrice', title: '最低活动价'});
            headData.push({field: 'enterpriceCode', title: '商品货号'});
            headData.push({field: 'barcode', title: '商品条形码'});
            headData.push({field: 'oldSpecCode', title: '旧规格码',});


            skuData.forEach((item, index) => {
                item.isShow = false;
                localSkuData.forEach((item1, index1) => {
                    if (item.skuName == item1.skuName) {
                        item.isShow = item1.isShow;
                    }
                })
            });

            localSkuData.forEach((item, index) => {
                if (localMap.has($(item.skuName).eq(1)[0].value)) {
                    item.isShow = true;
                }
            });
            var itb = table.render({
                elem: '#productSkuTable',
                data: skuData,
                page: false,
                height: 500,
                limit: Number.MAX_VALUE,
                cellMinWidth: 150,
                cols: [headData],
                done: function (res, curr, count) {
                    res.data.forEach(item => {
                        if (item.isShow == false) {
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('td:not(:first-child)').css({
                                cursor: 'not-allowed',
                                backgroundColor: '#cfcfcf'
                            });
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('input').css({
                                cursor: 'not-allowed',
                                backgroundColor: '#cfcfcf'
                            });
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('input').attr('disabled', 'disabled');
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('input').removeAttr('lay-verify');
                        } else {
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('td:not(:first-child)').css({
                                cursor: 'auto',
                                backgroundColor: 'none'
                            });
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('input').css({
                                cursor: 'auto',
                                backgroundColor: 'none'
                            });
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('input').removeAttr('disabled');
                            $("#" + $(item.skuName).eq(2)[0].id).parents('tr').find('input[type="text"]').attr('lay-verify', "required");
                        }
                    });

                    if (localMap) {
                        localMap.forEach(item => {
                            var specKey = item.skuSpecValue;
                            $("#skuName" + specKey).val(item.skuName);
                            $("#skuCode" + specKey).val(item.skuCode);
                            $("#spPrice" + specKey).val(item.spPrice);
                            $("#marketPrice" + specKey).val(item.marketPrice);
                            $("#supplyPrice" + specKey).val(item.supplyPrice);
                            $("#activityPrice" + specKey).val(item.activityPrice);
                            $("#enterpriceCode" + specKey).val(item.enterpriceCode);
                            $("#barcode" + specKey).val(item.barcode);
                            $("#skuId" + specKey).val(item.id);
                            $("#oldSpecCode" + specKey).val(item.oldSpecCode);

                            form.render();
                        })
                    }
                }
            });


            if (newCreateSkuMap.size > 0) {
                newCreateSkuMap.forEach(item => {
                    if (localMap.has(item.skuSpecValue)) {
                        let localMapVlue = Object.assign(newCreateSkuMap.get(item.skuSpecValue), item);
                        localMap.set(item.skuSpecValue, localMapVlue)
                    } else {
                        localMap.set(item.skuSpecValue, item)
                    }
                });
            }


            let localMapObj = {};

            $("body").delegate("input[name='skuName']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.skuName = $(this).val();
                    localMapObj.skuSpecValue = $(this).prev().val();
                    storageLocaData($(this), localMapObj);
                    // if (localMap.has($(this).prev().val())) {
                    //     localMap.set($(this).prev().val(), Object.assign(localMap.get($(this).prev().val()), localMapObj));
                    // } else {
                    //     localMap.set($(this).prev().val(), localMapObj);
                    // }
                }
            });

            $("body").delegate("input[name='skuCode']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.skuCode = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });
            $("body").delegate("input[name='oldSpecCode']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.oldSpecCode = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });

            $("body").delegate("input[name='spPrice']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.spPrice = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });

            $("body").delegate("input[name='marketPrice']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.marketPrice = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });

            $("body").delegate("input[name='supplyPrice']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.supplyPrice = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });

            $("body").delegate("input[name='activityPrice']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.activityPrice = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });

            $("body").delegate("input[name='enterpriceCode']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.enterpriceCode = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });
            $("body").delegate("input[name='barcode']", "change", function () {
                if (skuData[$(this).parents('tr').index()]) {
                    localMapObj = {};
                    localMapObj.barcode = $(this).val();
                    storageLocaData($(this), localMapObj);
                }
            });


            // 工具条点击事件
            table.on('tool(productSkuTable)', function (obj) {
                //console.log("....");
                var data = obj.data;
                if (obj.event === 'delete') { // 删除
                    //console.log("....");
                    layer.confirm("确定删除吗？", {}, function (i) {
                        layer.close(i);
                        //从表格数据中删除
                        skuData = skuData.filter(item => {
                            if (item.id == obj.data.id) {
                                return false;
                            }
                            return true;
                        });
                        itb.reload({data: skuData});
                        if (newCreateSkuMap) {
                            newCreateSkuMap.forEach(item => {
                                var specKey = item.skuSpecValue;
                                $("#skuName" + specKey).val(item.skuName);
                                $("#skuCode" + specKey).val(item.skuCode);
                                $("#spPrice" + specKey).val(item.spPrice);
                                $("#marketPrice" + specKey).val(item.marketPrice);
                                $("#supplyPrice" + specKey).val(item.supplyPrice);
                                $("#activityPrice" + specKey).val(item.activityPrice);
                                $("#enterpriceCode" + specKey).val(item.enterpriceCode);
                                $("#barcode" + specKey).val(item.barcode);
                                $("#skuId" + specKey).val(item.id);
                            })
                        }
                    });
                } else if (obj.event === 'frozen') {
                    localSkuData.forEach((item, index) => {
                        if (item.skuName === data.skuName) {
                            item.isShow = false;
                        }
                    });

                    skuData.forEach(item => {
                        if (item.skuName === data.skuName) {
                            item.isShow = false;
                        }

                    });
                    itb.reload({data: skuData});
                } else if (obj.event === 'thaw') {
                    localSkuData.forEach(item => {
                        if (item.skuName === data.skuName) {
                            item.isShow = true;
                        }
                    });

                    skuData.forEach(item => {
                        if (item.skuName === data.skuName) {
                            item.isShow = true;
                        }
                    });
                    itb.reload({data: skuData});
                }
            });

            //数据库中如果有记录则回显
            if (localMap) {
                localMap.forEach(item => {
                    var specKey = item.skuSpecValue;
                    $("#skuName" + specKey).val(item.skuName);
                    $("#skuCode" + specKey).val(item.skuCode);
                    $("#spPrice" + specKey).val(item.spPrice);
                    $("#marketPrice" + specKey).val(item.marketPrice);
                    $("#supplyPrice" + specKey).val(item.supplyPrice);
                    $("#activityPrice" + specKey).val(item.activityPrice);
                    $("#enterpriceCode" + specKey).val(item.enterpriceCode);
                    $("#barcode" + specKey).val(item.barcode);
                    $("#skuId" + specKey).val(item.id);
                    $("#oldSpecCode" + specKey).val(item.oldSpecCode);
                    form.render();
                })
            }
        }

        function storageLocaData(ele, _localMapObj) {
            if (!ele || !_localMapObj) {
                return false;
            }
            if (localMap.has(ele.parents('tr').find('input[name="skuSpecValue"]').val())) {
                localMap.set(ele.parents('tr').find('input[name="skuSpecValue"]').val(), Object.assign(localMap.get(ele.parents('tr').find('input[name="skuSpecValue"]').val()), _localMapObj));
            } else {
                localMap.set(ele.parents('tr').find('input[name="skuSpecValue"]').val(), _localMapObj);
            }
        }


        function createSku(datas) {
            var index = 0;
            var first = datas[index];
            while (index < datas.length) {

                index++;
                if (index >= datas.length) {
                    break;
                }
                var second = datas[index];
                var size = first.length * second.length;
                var temp = [];
                var m = 0;
                for (var i = 0; i < first.length; i++) {
                    for (var j = 0; j < second.length; j++) {
                        temp[m++] = first[i] + "_" + second[j];
                    }
                }
                first = temp;
            }
            //console.log(first);
            return first;
        }

        function createProductSpec(data) {
            //alert("");
            $("[lay-id=productSkuTable] table").remove();
            if (null == data.value || "" == data.value) {
                layer.msg("请先选择物料类型！", {icon: 2});
                return;
            }

            $("[name='productSpecHtml']").html("");
            $("[name='productSpecValueHtml']").html("");
            $("[name='productSkuTable']").html("");
            //form.render();
            //console.log(data.value); //得到被选中的值
            //加载商品规格
            admin.req('enterprise/product/admin/productSpec/getProductSpecByProductTypeId', {productTypeId: data.value}, function (res) {
                let html = '';
                var data = res.data;
                if (!data || data == null) {
                    layer.msg("物料类型规格为空,请先前往配置物料规格！", {icon: 2});
                    return;
                }
                for (let i = 0; i < data.length; i++) {
                    html += '<input lay-filter="productSpec" specHead="' + data[i].specHead + '" specLocation="' + data[i].specLocation + '" specCode="' + data[i].specCode + '" id="productSpec" type="checkbox" name  = "productSpec" value="' + data[i].id + '" lay-skin="primary" title="' + data[i].name + '" >';
                }
                //console.log(html);
                $("[name='productSpecHtml']").html(html);
                form.render();
            }, 'get', false);

            createProductSpecValueSku();
        }



        //生成平台规格和规格值
        function createPloatformSpecValue(data) {

            if (null == data) {
                return;
            }
            var html = '';
            console.log(data)
            data.forEach((elem, index) => {
                var subItem = elem.productSpecValueList;
                html += '<div style="margin-top: 20px" name="platformProductSpec' + elem.id + '">';
                html += '<div class="layui-form-item">';
                html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + elem.name + ':</label>';
                html += '<div class="layui-input-block" style="width: 200px;">';
                html += '<select name="platformProductValue' + elem.id + '" lay-filter="platformProductValue" id="platformProductValue' + elem.id + '"><option id="">请选择规格值</option>';

                subItem.forEach((subElem, index) => {
                    html += '<option id="' + elem.id + '_' + subElem.id + '">' + subElem.value + '</option>';
                })

                html += '</select>';
                html += '</div>';
                html += '</div>';
                html += '</div>';


            })
            $("#platformSpec").html(html);
            form.render();
            form.on('select(platformProductValue)', function (data1) {
                var platformProductSpecValueName = "";
                var platformProductSpecValueId = "";
                var platformProductSpecId = "";
                data.forEach((elem1, index) => {

                    var temp = $("#platformProductValue" + elem1.id).val()
                    var tempId = $("#platformProductValue" + elem1.id + " option:checked").attr("id");
                    if ("请选择规格值" == temp) {
                        return;
                    }
                    var specArr = tempId.split("_");
                    if (elem1.specCode == 'is') {
                        if (elem1.specLocation == 'last') {
                            temp = temp + elem1.specHead
                        } else if (elem1.specLocation == 'before') {
                            temp = elem1.specHead + temp;
                        }
                    }


                    platformProductSpecValueName += temp + "-";
                    platformProductSpecId += specArr[0] + "_";
                    platformProductSpecValueId += specArr[1] + "_";
                })
                //alert(productSpec);
                platformProductSpecValueName = platformProductSpecValueName.substring(platformProductSpecValueName, platformProductSpecValueName.length - 1);
                platformProductSpecId = platformProductSpecId.substring(platformProductSpecId, platformProductSpecId.length - 1);
                platformProductSpecValueId = platformProductSpecValueId.substring(platformProductSpecValueId, platformProductSpecValueId.length - 1);

                $("#platformProductSpecValueName").html(platformProductSpecValueName);
                $("#platformProductSpecValueId").val(platformProductSpecValueId);
                $("#platformProductSpecId").val(platformProductSpecId);

            })

        }

        //多规格参数
        let productSpecValueByProductSpecValueIds = new Map();
        let productSpecValueByProductSpecValueIdsStr = '';

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '800px',
                offset: '65px',
                title: data ? '修改生产产品系列' : '添加生产产品系列',
                content: $('#productForm').html(),
                success: function () {
                    var dbSkuMap = new Map();
                    productSpecValueByProductSpecValueIds.clear();
                    productSpecValueByProductSpecValueIdsStr = '';
                    localMap.clear();
                    localSkuData = [];
                    //加载物料类型
                    admin.req('enterprise/product/admin/productType/getProductTypeByType', {}, function (res) {
                        loadSelectHtml(res.data, "请选择物料类型", "productTypeId", "name");
                        if (data) {
                            $("#productTypeId").val(data.productTypeId);
                            form.render('select');
                        }
                    }, 'get', false);

                    /*admin.reqSync('enterprise/product/admin/productSeriesWMS/platformProductSeriesList', {}, function (res) {
                        if (res.code==200) {
                            var html='<option value="">请选择平台系列</option>';
                            for(var k=0;k<res.data.length;k++){
                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                            }
                            $("select[name='idPlatform']").html(html);
                            form.render('select');
                        } else {
                            layer.msg('获取平台物料系列失败', {icon: 2, time: 1000});
                        }
                        if(data){
                            $("select[name='idPlatform']").val(data.idPlatform);
                            form.render('select');
                        }
                    }, 'GET');*/

                    //加载物料分类树级菜单
                    var arr2tree;
                    admin.req('enterprise/product/admin/productCategory/getProductCategoryByType', {categoryType: 'production'}, function (res) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].children = [];
                        }
                        arr2tree = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
                    }, 'get', false);

                    var selectedData = function (treeData, targetId) {

                        for (var k = 0; k < treeData.length; k++) {
                            var nodeId = treeData[k].id;
                            if (targetId == nodeId) {
                                treeData[k].selected = true;
                                return;
                            } else {
                                if (treeData[k].children && treeData[k].children != '') {
                                    selectedData(treeData[k].children, targetId);
                                }
                            }
                        }
                    }

                    if (data) {
                        selectedData(arr2tree, data.productCategoryId);
                    }

                    var smlSelectInstans = xmSelect.render({
                        el: '#productCategoryId',
                        model: {label: {type: 'text'}},
                        radio: true,
                        clickClose: true,
                        filterable: true,
                        tree: {
                            show: true,
                            strict: false,
                            expandedKeys: [-1],
                        },
                        tips: '顶级分类',
                        prop: {
                            name: 'name',
                            value: 'id',
                            children: 'children'
                        },
                        data() {
                            //填充数据
                            return arr2tree;
                        },
                        on(data) {
                            let parentId = data.arr.length > 0 ? data.change[0].id : -1;
                            $("input[name='productCategoryId']").val(parentId);
                        }
                    });

                    //加载扩展物料分类树级菜单
                    var arr2treeExt;
                    admin.req('enterprise/product/admin/productCategory/getProductCategoryByType', {categoryType: 'production'}, function (res) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].children = [];
                        }
                        arr2treeExt = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
                    }, 'get', false);

                    var selectedDataExt = function (treeData, targetId) {
                        var ids = targetId.split(",");
                        for (var k = 0; k < treeData.length; k++) {
                            var nodeId = treeData[k].id;
                            for (var t = 0; t < ids.length; t++) {
                                if (ids[t] == nodeId) {
                                    treeData[k].selected = true;
                                    continue;
                                } else {
                                    if (treeData[k].children && treeData[k].children != '') {
                                        selectedData(treeData[k].children, ids[t]);
                                    }
                                }
                            }
                        }
                    }

                    if (data) {
                        selectedDataExt(arr2treeExt, data.productCategoryExtId);
                    }
                    var smlSelectInstansExt = xmSelect.render({
                        el: '#productCategoryExt',
                        model: {label: {type: 'text'}},
                        //radio: true,
                        clickClose: true,
                        filterable: true,
                        tree: {
                            show: true,
                            strict: false,
                            expandedKeys: [-1],
                        },
                        tips: '顶级分类',
                        prop: {
                            name: 'name',
                            value: 'id',
                            children: 'children'
                        },
                        data() {
                            //填充数据
                            return arr2treeExt;
                        }
                    });


                    //加载品牌
                    admin.req('enterprise/product/admin/productBrand/getAllProductBrandByType', {type: 0}, function (res) {
                        loadSelectHtml(res.data, "请选择品牌", "brandId", "name");
                        if (data) {
                            $("#brandId").val(data.brandId);
                            form.render('select');
                        }
                    }, 'get', false);

                    var productAttrData;

                    form.on('select(productTypeId)', function (data) {
                        admin.req('enterprise/product/admin/productAttribute/getProductAttrByProductTypeId', {productTypeId: data.value}, function (res) {
                            productAttrData = res.data;
                        }, 'get', false);
                        //创建物料规格
                        createProductSpec(data);

                        //加载物料单位
                        admin.req('enterprise/product/admin/productUnit/getProductUnitByType', {
                            type: 0,
                            productTypeId: data.value
                        }, function (res) {
                            console.log(res.data)
                            loadSelectHtml(res.data, "请选择单位", "unitId", "name");
                            if (data) {
                                $("#unitId").val(data.unitId);
                                form.render('select');
                            }
                        }, 'get', false);
                    });
                    form.on('checkbox(productSpec)', function (data) {
                        if (data.elem.checked) {
                            admin.req('enterprise/product/admin/productSpecValue/getProductSpecValueByProductSpecId', {productSpecId: data.value}, function (res) {
                                //console.log("规格值：" + data.value);
                                var html = loadSpecValueHtml(res.data, data.elem.title, data.value);
                                //console.log(html);
                                $("[name='productSpecValueHtml']").html($("[name='productSpecValueHtml']").html() + html);
                                form.render();
                            }, 'get', false);
                        } else {
                            $("[name='specValue" + data.elem.title + "']").html("");
                            form.render();
                        }
                        localSkuData = [];
                        localMap.clear();
                        createProductSpecValueSku(dbSkuMap);
                    });

                    form.on('checkbox(productSpecValue)', function (data) {
                        createProductSpecValueSku(dbSkuMap);

                    });


                    //查询企业信息
                   /* var enterpriseInfo;
                    admin.req('enterprise/system/admin/system/getLoginInfo', {}, function (res) {
                        enterpriseInfo = res.data;
                    }, 'get', false);
                    if ("" == enterpriseInfo || null == enterpriseInfo) {
                        layer.msg("企业信息获取异常", {icon: 1});
                        return;
                    }*/
                    //var productCode = $("input[name='productCode']").val();
                    upload.render({
                        elem: '#btnUpload14'
                        , url: config.upload_url + 'uploadFile'
                        , data: {}
                        , accept: 'file'
                        , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                        , headers: {Authorization: 'Bearer ' + config.getToken()}
                        , done: function (res) {
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                var imagUrl = res.data.url;
                                // if(imagUrl){
                                //     imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                // }
                                $('#btnUpload14_path').html('<img src="' + imagUrl + '" style="height: 50px;" />');
                                $('#picture').val(imagUrl);
                            } else if (res.code == 502) {
                                return location.replace('admin/login.html');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });

                    if (data && data.picture) {
                        $('#btnUpload14_path').html('<img src="' + data.picture + '" style="height: 50px;" />');
                    }
                    var layeditIndex18 = layedit.build('description', {
                        uploadImage: {
                            url: config.upload_url + 'uploadFile',
                            type: 'post',
                            data: {},
                            base: config.base,
                            before: function (obj) {
                                layer.load(); //上传loading
                                this.headers = {Authorization: 'Bearer ' + config.getToken()};
                                this.data = {};
                            }
                        }
                    });

                    if (data) {
                        $("#productCode_edit").attr("disabled", "disabled");
                        form.render();
                        layedit.setContent(layeditIndex18, data.description, false);

                        //回显商品属性
                        admin.req('enterprise/product/admin/productAttribute/getProductAttrByProductTypeId', {productTypeId: data.productTypeId}, function (res) {
                            createProductAttr(res.data);
                        }, 'get', false);

                        for (var k = 0; k < data.productDetailAttribute.length; k++) {
                            var attrObj = data.productDetailAttribute[k];
                            var arrrValueObj = attrObj.productDetailAttributeValue;
                            if (attrObj.style == 'single') {
                                $("#productAttrValue" + attrObj.attrId).val(arrrValueObj[0].valueId);
                            }
                            if (attrObj.style == 'many') {
                                var checkboxArr = $("input[name='productAttrValue" + attrObj.attrId + "']");
                                for (let j = 0; j < checkboxArr.length; j++) {
                                    for (var i = 0; i < arrrValueObj.length; i++) {
                                        if ($(checkboxArr[j]).val() == arrrValueObj[i].valueId) {
                                            $(checkboxArr[j]).prop("checked", "checked")
                                        }
                                    }
                                }
                            }
                            if (attrObj.style == 'text') {
                                $("#productAttrValue" + attrObj.attrId).val(attrObj.attrValue);
                            }
                        }
                        form.render();
                        //回显SKU明细
                        //var itemSub = data.productDetialList;
                        admin.req('enterprise/product/admin/productDetail/getProductDetailByProductId', {productId: data.id}, function (res) {
                            //初始化物料规格
                            var itemSub = res.data;
                            //去重的商品规格ID
                            var productSpecId = [];
                            var productSpecValueId = [];
                            for (var i = 0; i < itemSub.length; i++) {
                                var arrSpec = itemSub[i].skuSpec.split("_");
                                var arrSpecValue = itemSub[i].skuSpecValue.split("_");
                                for (var j = 0; j < arrSpec.length; j++) {
                                    productSpecId.push(arrSpec[j]);
                                }
                                for (var j = 0; j < arrSpecValue.length; j++) {
                                    productSpecValueId.push(arrSpecValue[j]);
                                }
                            }
                            var skuSpecId = unique(productSpecId);
                            createProductSpec({value: data.productTypeId});

                            var checkboxArr = $("input[name='productSpec']");
                            for (let j = 0; j < checkboxArr.length; j++) {
                                for (var i = 0; i < skuSpecId.length; i++) {
                                    if ($(checkboxArr[j]).val() == skuSpecId[i]) {
                                        $(checkboxArr[j]).prop("checked", "checked")
                                    }
                                }
                            }


                            //初始化物料规格值
                            var productSpecMap = new Map();
                            admin.req('enterprise/product/admin/productSpec/getProductSpecByProductTypeId', {productTypeId: data.productTypeId}, function (res) {
                                var data = res.data;
                                for (var i = 0; i < data.length; i++) {
                                    productSpecMap.set(data[i].id, data[i].name);
                                }

                            }, 'get', false);
                            //去重
                            for (var i = 0; i < skuSpecId.length; i++) {
                                //创建物料规格值列表
                                admin.req('enterprise/product/admin/productSpecValue/getProductSpecValueByProductSpecId', {productSpecId: skuSpecId[i]}, function (res) {
                                    //console.log("规格值：" + data.value);
                                    var html = loadSpecValueHtml(res.data, productSpecMap.get(skuSpecId[i]), skuSpecId[i]);
                                    //console.log(html);
                                    $("[name='productSpecValueHtml']").html($("[name='productSpecValueHtml']").html() + html);
                                }, 'get', false);
                            }
                            form.render();

                            //商品规格值回显
                            var skuSpecValueId = unique(productSpecValueId);
                            for (var i = 0; i < skuSpecId.length; i++) {
                                var checkboxArr = $("input[name='productSpecValue" + skuSpecId[i] + "']");
                                for (let j = 0; j < checkboxArr.length; j++) {
                                    for (var k = 0; k < skuSpecValueId.length; k++) {
                                        if ($(checkboxArr[j]).val() == skuSpecValueId[k]) {
                                            $(checkboxArr[j]).prop("checked", "checked")
                                        }
                                    }
                                }
                            }


                            //物料SKU数据回填
                            /*itemSub.forEach(item => {
                                dbSkuMap.set(item.skuSpecValue, item);
                            })*/
                            createProductSpecValueSku(dbSkuMap);
                            for (var k = 0; k < itemSub.length; k++) {
                                $("#skuName" + itemSub[k].skuSpecValue).val(itemSub[k].skuName);
                                $("#skuCode" + itemSub[k].skuSpecValue).val(itemSub[k].skuCode);
                                $("#spPrice" + itemSub[k].skuSpecValue).val(itemSub[k].spPrice);
                                $("#marketPrice" + itemSub[k].skuSpecValue).val(itemSub[k].marketPrice);
                                $("#supplyPrice" + itemSub[k].skuSpecValue).val(itemSub[k].supplyPrice);
                                $("#activityPrice" + itemSub[k].skuSpecValue).val(itemSub[k].activityPrice);
                                $("#enterpriceCode" + itemSub[k].skuSpecValue).val(itemSub[k].enterpriceCode);
                                $("#barcode" + itemSub[k].skuSpecValue).val(itemSub[k].barcode);
                                $("#skuId" + itemSub[k].skuSpecValue).val(itemSub[k].id);
                                $("#oldSpecCode" + itemSub[k].oldSpecCode).val(itemSub[k].oldSpecCode);
                                form.render();
                            }

                        }, 'get', false);

                    }


                    form.val('productForm', data);
                    // 表单提交事件
                    form.on('submit(productFormSubmit)', function (d) {
                        //console.log(d.field);
                        // layer.load(2);
                        //获取SKU行数据
                        //获取所有行
                        let row = $("[lay-id=productSkuTable] table tbody tr");
                        //遍历所有行
                        let listData = [];
                        for (var i = 0; i < row.length; i++) {
                            //console.log(row);skuSpesValueName
                            var skuSpec = row.eq(i).find("input").eq(0).val();
                            var skuSpecValue = row.eq(i).find("input").eq(1).val();
                            var skuName = row.eq(i).find("input").eq(2).val();
                            // var skuSpecValueNames = row.eq(i).find("input").eq(3).val();
                            let skuSpecValueNames = row.eq(i).find("span[name='skuSpecValueNamesSpan']").text();
                            var skuCode = row.eq(i).find("input").eq(4).val();
                            var spPrice = row.eq(i).find("input").eq(5).val();
                            var marketPrice = row.eq(i).find("input").eq(6).val();
                            var supplyPrice = row.eq(i).find("input").eq(7).val();
                            var activityPrice = row.eq(i).find("input").eq(8).val();
                            var enterpriceCode = row.eq(i).find("input").eq(9).val();
                            var barcode = row.eq(i).find("input").eq(10).val();
                            let oldSpecCode = row.eq(i).find("input").eq(12).val();
                            let subData = {
                                skuSpec: skuSpec,
                                skuSpecValue: skuSpecValue,
                                skuName: skuName,
                                skuSpecValueNames: skuSpecValueNames,
                                skuCode: skuCode,
                                spPrice: spPrice,
                                marketPrice: marketPrice,
                                supplyPrice: supplyPrice,
                                activityPrice: activityPrice,
                                enterpriceCode: enterpriceCode,
                                barcode: barcode,
                                oldSpecCode: oldSpecCode
                            };
                            listData.push(subData)
                        }


                        localSkuData.forEach(item => {
                            if (item.isShow == false) {
                                listData.forEach((item1, index1) => {
                                    if ($(item.skuName).eq(1)[0].value == item1.skuSpecValue) {
                                        listData.splice(index1, 1);
                                    }
                                })
                            }
                        });
                        d.field.productDetailForm = listData;
                        //获取商品属性
                        var attrArry = [];
                        var productAttrData;
                        var productTypeId = $("#productTypeId").val();
                        admin.req('enterprise/product/admin/productAttribute/getProductAttrByProductTypeId', {productTypeId: productTypeId}, function (res) {
                            productAttrData = res.data;
                        }, 'get', false);
                        for (var k = 0; k < productAttrData.length; k++) {
                            var obj = productAttrData[k];
                            //多选 获取值
                            var subAttrArry = [];
                            if (obj.style == 'many') {
                                $("input:checkbox[name='productAttrValue" + obj.id + "']:checked").each(function (i) {
                                    var subArrrObj = {
                                        attrId: obj.id,
                                        value: $(this).attr('title'),
                                        valueId: $(this).val()
                                    };
                                    subAttrArry.push(subArrrObj);
                                });
                                if (subAttrArry.length > 0) {
                                    var attrObj = {
                                        attrId: obj.id,
                                        attrName: obj.name,
                                        productDetailAttributeValueForm: subAttrArry,
                                        style: 0
                                    };
                                    attrArry.push(attrObj);
                                }
                            }
                            //单选 获取值
                            if (obj.style == 'single') {
                                var selectVal = $("#productAttrValue" + obj.id).val();
                                var selectName = $("#productAttrValue" + obj.id).find("option:selected").text();

                                if (selectVal != '') {
                                    var subArrrObj = {
                                        attrId: obj.id,
                                        value: selectName,
                                        valueId: selectVal
                                    };
                                    subAttrArry.push(subArrrObj);
                                }
                                if (subAttrArry.length > 0) {
                                    var attrObj = {
                                        attrId: obj.id,
                                        attrName: obj.name,
                                        productDetailAttributeValueForm: subAttrArry,
                                        style: 1
                                    };
                                    attrArry.push(attrObj);
                                }
                            }

                            //文本 获取值
                            if (obj.style == 'text') {
                                var selectVal = $("#productAttrValue" + obj.id).val();
                                if (selectVal != '') {
                                    var attrObj = {
                                        attrId: obj.id,
                                        attrName: obj.name,
                                        attrValue: selectVal,
                                        style: 2
                                    };
                                    attrArry.push(attrObj);
                                }
                            }
                        }

                        d.field.productDetailAttributeForm = attrArry;

                        d.field.productCategoryExtId = d.field.select;
                        d.field.description = layedit.getContent(layeditIndex18);
                        var a = JSON.stringify(d.field);
                        admin.req(data ? 'enterprise/product/admin/productSeriesWMS/update' : 'enterprise/product/admin/productSeriesWMS/add', JSON.stringify(d.field), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('productTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST', true, 'application/json; charset=utf-8');
                        return false;
                    });
                }

            });
        }

        function unique(arr) {
            return arr.filter((item, index) => {
                // console.log(item, index);
                // console.log(arr.indexOf(item)+'---'+index
                // 第一次 cc 索引2 过滤后的索引2
                // 第二次 cc 索引2 过滤后的索引3
                // 后面去重以此类推
                return arr.indexOf(item) == index
            })
        }

        // 添加按钮点击事件
        $('#productBtnAdd').click(function () {
            showEditModel();
        });

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/product/admin/productSeriesWMS/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }
        function cancellation(data){
            layer.confirm('确定作废吗？', {
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.reqSync('enterprise/product/admin/productSeriesWMS/disable?id='+data.id+"&type=1",{}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        table.reload('productTable');
                        layer.msg("作废成功！")
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                }, 'GET');
            });

        }

        function openTable(data){
            layer.confirm('确定开启吗？', {
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.reqSync('enterprise/product/admin/productSeriesWMS/disable?id='+data.id+"&type=0",{}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        table.reload('productTable');
                        layer.msg("开启成功！")
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                }, 'GET');
            });

        }
        // 导出excel
        $('#productBtnExport').click(function () {
            var checkRows = table.checkStatus('productTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

        var subData = [];

        // 同步SKU到平台
        function doSynsSku(obj) {
            var data = obj.data;
            admin.open({
                type: 1,
                area: '1600px',
                offset: '65px',
                title: '同步物料到云端',
                content: $('#synsSkuForm').html(),
                success: function () {

                    //查询企业信息
                   /* var enterpriseInfo;
                    admin.req('enterprise/system/admin/system/getLoginInfo', {}, function (res) {
                        enterpriseInfo = res.data;
                    }, 'get', false);*/

                    $("#enterprisePic").attr("src", data.picture);
                    $("#enterpriseItemPic").val(data.picture);
                    $("#enterpriseName").val(data.name);
                    $("#enterpriseProductCode").val(data.productCode);
                    $("#enterpriseProductType").val(data.productTypeName);
                    $("#enterpriseProductCategory").val(data.productCategoryName);
                    $("#enterpriseProductCategoryExt").val(data.productCategoryExtName);
                    $("#enterpriseBrand").val(data.brandName);
                    $("#enterpriseCode").val(data.enterpriseCode);
                    //$("#platformProductCode").val(data.enterpriseCode +"_"+ data.productCode);
                    $("#platformName").val(data.name);
                    $('#btnUpload1Syns_path').html('<img src="' + data.picture + '" style="height: 135px;width: 135px" />');
                    $('#pictureSyns').val(data.picture);

                    //回显商品属性
                    admin.req('enterprise/product/admin/productAttribute/getProductAttrByProductTypeId', {productTypeId: data.productTypeId}, function (res) {
                        createEnterpriseProductAttr(res.data);
                    }, 'get', false);


                    for (var k = 0; k < data.productDetailAttribute.length; k++) {
                        var attrObj = data.productDetailAttribute[k];
                        var arrrValueObj = attrObj.productDetailAttributeValue;
                        if (attrObj.style == 'single') {
                            $("#enterpriseProductAttrValue" + attrObj.attrId).val(arrrValueObj[0].valueId);
                        }
                        if (attrObj.style == 'many') {
                            var checkboxArr = $("input[name='enterpriseProductAttrValue" + attrObj.attrId + "']");
                            for (let j = 0; j < checkboxArr.length; j++) {
                                for (var i = 0; i < arrrValueObj.length; i++) {
                                    if ($(checkboxArr[j]).val() == arrrValueObj[i].valueId) {
                                        $(checkboxArr[j]).prop("checked", "checked")
                                    }
                                }
                            }
                        }
                        if (attrObj.style == 'text') {
                            $("#enterpriseProductAttrValue" + attrObj.attrId).val(attrObj.attrValue);
                        }
                    }
                    form.render();

                    //加载物料类型
                    admin.req('enterprisecab/productCab/admin/product/getProductTypeByType', {type: 0}, function (res) {
                        loadSelectHtml(res.data.data, "请选择物料类型", "platformProductTypeId", "name");
                    }, 'get', false);

                    //加载物料分类树级菜单
                    var arr2tree;
                    admin.req('enterprisecab/productCab/admin/product/getProductCategoryByType', {type: 0}, function (res) {
                        if (res.code == 200) {
                            for (let i = 0; i < res.data.length; i++) {
                                res.data[i].children = [];
                            }
                            arr2tree = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
                        }
                    }, 'get', false);


                    var smlSelectInstans = xmSelect.render({
                        el: '#platformProductCategoryId',
                        model: {label: {type: 'text'}},
                        radio: true,
                        clickClose: true,
                        filterable: true,
                        tree: {
                            show: true,
                            strict: false,
                            expandedKeys: [-1],
                        },
                        tips: '顶级分类',
                        prop: {
                            name: 'name',
                            value: 'id',
                            children: 'children'
                        },
                        data() {
                            //填充数据
                            return arr2tree;
                        },
                        on(data) {
                            let parentId = data.arr.length > 0 ? data.change[0].id : -1;
                            $("input[name='platformProductCategoryId']").val(parentId);
                        }
                    });
                    //加载扩展物料分类树级菜单
                    var arr2treeExt;
                    admin.req('enterprisecab/productCab/admin/product/getProductCategoryByType', {type: 0}, function (res) {
                        if (res.code == 200) {
                            for (let i = 0; i < res.data.length; i++) {
                                res.data[i].children = [];
                            }
                            arr2treeExt = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
                        }
                    }, 'get', false);

                    var smlSelectInstansExt = xmSelect.render({
                        el: '#platformProductCategoryExt',
                        model: {label: {type: 'text'}},
                        //radio: true,
                        clickClose: true,
                        filterable: true,
                        tree: {
                            show: true,
                            strict: false,
                            expandedKeys: [-1],
                        },
                        tips: '顶级分类',
                        prop: {
                            name: 'name',
                            value: 'id',
                            children: 'children'
                        },
                        data() {
                            //填充数据
                            return arr2treeExt;
                        },
                        on: function (data) {
                            var id = '';
                            for (var j = 0; j < data.arr.length; j++) {
                                if (j == 0) {
                                    id = data.arr[j].id
                                } else {
                                    id += ',' + data.arr[j].id;
                                }
                            }
                            $("input[name='platformProductCategoryIdExt']").val(id)
                        }
                    });

                    //加载品牌
                    admin.req('enterprisecab/productCab/admin/product/getProductBrandByType', {type: 0}, function (res) {
                        loadSelectHtmlByCode(res.data, "请选择品牌", "platformBrandId", "name");
                    }, 'get', false);

                    var productAttrData;

                    form.on('select(platformProductTypeId)', function (data) {
                        admin.req('enterprisecab/productCab/admin/product/getProductAttrByProductTypeId', {productTypeId: data.value}, function (res) {
                            productAttrData = res.data;
                        }, 'get', false);
                        //创建物料属性
                        createPlatformProductAttr(productAttrData);

                        //加载物料单位
                        admin.req('enterprisecab/productCab/admin/product/getProductUnitByType', {
                            type: 0,
                            productTypeId: data.value
                        }, function (res) {
                            loadSelectHtmlByCode(res.data, "请选择单位", "platformUnitId", "name");
                        }, 'get', false);
                    });
                    function createPlatformProductAttr(data) {
                        let html = '';
                        if (!data || data == null) {
                            return;
                        }
                        for (let i = 0; i < data.length; i++) {
                            //多选
                            if (data[i].style == 'many') {
                                html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                                html += '<div class="layui-form-item">';
                                html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                                html += '<div class="layui-input-block">';

                                for (let j = 0; j < data[i].productAttributeValue.length; j++) {
                                    var subData = data[i].productAttributeValue[j];
                                    html += '<input lay-filter="platformProductAttrValue' + data[i].id + '" type="checkbox" name  = "platformProductAttrValue' + data[i].id + '"  value="' + subData.id + '" lay-skin="primary" title="' + subData.value + '">';
                                }
                                html += '</div>';
                                html += '</div>';
                                html += '</div>';
                            }
                            //单选
                            if (data[i].style == 'single') {
                                html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                                html += '<div class="layui-form-item">';
                                html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                                html += '<div class="layui-input-block">';
                                html += '<select lay-filter="platformProductAttrValue' + data[i].id + '"  name="platformProductAttrValue' + data[i].id + '" id="platformProductAttrValue' + data[i].id + '" lay-verify="required">';
                                html += '<option value="">请选择属性</option>';
                                for (let j = 0; j < data[i].productAttributeValue.length; j++) {
                                    var subData = data[i].productAttributeValue[j];
                                    html += '<option value="' + subData.id + '">' + subData.value + '</option>';
                                }
                                html += "</select>";
                                html += '</div>';
                                html += '</div>';
                                html += '</div>';
                            }
                            //文本
                            if (data[i].style == 'text') {
                                html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                                html += '<div class="layui-form-item">';
                                html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                                html += '<div class="layui-input-block">';
                                html += '<input type="text" class="layui-input" lay-filter="platformProductAttrValue' + data[i].id + '" name="platformProductAttrValue' + data[i].id + '" id="platformProductAttrValue' + data[i].id + '" lay-verify="required" />';
                                html += '</div>';
                                html += '</div>';
                                html += '</div>';
                            }
                        }
                        //console.log(html);
                        $("[name='platformProductAttrHtml']").html(html);
                        form.render();

                    }
                    // for(var k=0;k<data.productDetailAttribute.length;k++){
                    //     var attrObj = data.productDetailAttribute[k];
                    //     var arrrValueObj = attrObj.productDetailAttributeValue;
                    //     if(attrObj.style == 'single'){
                    //         $("#platformProductAttrValue" + attrObj.attrId).val(arrrValueObj[0].valueId);
                    //     }
                    //     if(attrObj.style == 'many'){
                    //         var checkboxArr = $("input[name='platformProductAttrValue"+ attrObj.attrId+"']");
                    //         for (let j = 0; j < checkboxArr.length; j++) {
                    //             for(var i=0;i<arrrValueObj.length;i++){
                    //                 if ($(checkboxArr[j]).val() == arrrValueObj[i].valueId) {
                    //                     $(checkboxArr[j]).prop("checked", "checked")
                    //                 }
                    //             }
                    //         }
                    //     }
                    //     if(attrObj.style == 'text'){
                    //         $("#platformProductAttrValue" + attrObj.attrId).val(attrObj.attrValue);
                    //     }
                    // }
                    //form.render();

                    upload.render({
                        elem: '#btnUpload1Syns'
                        , url: config.upload_url + 'upload?path=' + img_path
                        , data: {}
                        , accept: 'file'
                        , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                        , headers: {Authorization: 'Bearer ' + config.getToken()}
                        , done: function (res) {
                            if (res.code == 200) {
                                layer.msg(res.msg || "上传成功", {icon: 1});
                                var imagUrl = res.data.url;
                                // if(imagUrl){
                                //     imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                // }
                                $('#btnUpload1Syns_path').html('<img src="' + imagUrl + '" style="height: 135px;width: 135px" />');
                                $('#pictureSyns').val(imagUrl);
                            } else if (res.code == 502) {
                                return location.replace('admin/login.html');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });

                    admin.req('enterprise/product/admin/productDetail/getProductDetailByProductId', {productId: data.id}, function (res) {

                        subData = res.data;
                        subData.forEach((emel, index) => {
                            emel.platformSkuCode = data.enterpriseCode + "_" + emel.skuCode
                        })
                        //展示SKU信息
                        createSkuTable(subData, data);
                    });


                }
            })

        }
        function createProductAttr(data) {
            let html = '';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                //多选
                if (data[i].style == 'many') {
                    html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                    html += '<div class="layui-form-item">';
                    html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                    html += '<div class="layui-input-block">';

                    for (let j = 0; j < data[i].productAttributeValue.length; j++) {
                        var subData = data[i].productAttributeValue[j];
                        html += '<input lay-filter="productAttrValue' + data[i].id + '" type="checkbox" name  = "productAttrValue' + data[i].id + '"  value="' + subData.id + '" lay-skin="primary" title="' + subData.value + '">';
                    }
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                }
                //单选
                if (data[i].style == 'single') {
                    html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                    html += '<div class="layui-form-item">';
                    html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                    html += '<div class="layui-input-block">';
                    html += '<select lay-filter="productAttrValue' + data[i].id + '"  name="productAttrValue' + data[i].id + '" id="productAttrValue' + data[i].id + '" lay-verify="required">';
                    html += '<option value="">请选择属性</option>';
                    for (let j = 0; j < data[i].productAttributeValue.length; j++) {
                        var subData = data[i].productAttributeValue[j];
                        html += '<option value="' + subData.id + '">' + subData.value + '</option>';
                    }
                    html += "</select>";
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                }
                //文本
                if (data[i].style == 'text') {
                    html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                    html += '<div class="layui-form-item">';
                    html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                    html += '<div class="layui-input-block">';
                    html += '<input type="text" class="layui-input" lay-filter="productAttrValue' + data[i].id + '" name="productAttrValue' + data[i].id + '" id="productAttrValue' + data[i].id + '" lay-verify="required" />';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                }
            }
            //console.log(html);
            $("[name='productAttrHtml']").html(html);
            form.render();

        }
        function createSkuTable(subData, data) {
            var itb = table.render({
                elem: '#platformProductSkuTable',
                data: subData,
                page: false,
                cellMinWidth: 60,
                cols: [[
                    {field: 'id', sort: true, title: '序号'}
                    , {field: 'skuCode', sort: true, title: '物料编号'}
                    , {
                        field: 'productPic', sort: true, title: '图片', templet: function (d) {
                            return '<img src="' + data.picture + '" style="height: 75px;width: 75px" id="platformPic"/>'
                        }
                    }
                    , {field: 'skuName', sort: true, title: '物料名称'}
                    , {field: 'skuSpecValueNames', sort: true, title: '企业物料规格'}
                    , {field: 'isSynsDes', sort: true, title: '同步到云端'}
                    , {field: 'platformSkuCode', sort: true, title: '平台物料码'}
                    , {field: 'supplyPrice', sort: true, title: '平台供货价'}
                    , {field: 'spPrice', sort: true, title: '渠道价'}
                    , {field: 'marketPrice', sort: true, title: '市场指导价'}
                    , {field: 'activityPrice', sort: true, title: '最低活动价'}
                    , {
                        field: 'platformSkuSpec', sort: true, title: '平台规格参数', templet: function (d) {
                            return '<div class="layui-form-label w-120" id="platformSpecValueTb' + d.skuCode + '"></div><input type="hidden" id="platformSpecValueIdTb' + d.skuCode + '" name="platformSpecValueIdTb' + d.skuCode + '" value=""><input type="hidden" id="platformSpecIdTb' + d.skuCode + '" name="platformSpecIdTb' + d.skuCode + '" value="">'
                        }
                    }
                    , {align: 'center', toolbar: '#synsSkuTableBar', title: '操作', width: 300}
                ]]
            });
            table.render(itb);
        }

        // 工具条点击事件
        table.on('tool(platformProductSkuTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'settingSpec') { //设置平台规格
                var platformProductTypeId = $("#platformProductTypeId").val();
                if (null == platformProductTypeId || platformProductTypeId == '') {
                    layer.msg("请选选择平台物料类型！", {icon: 2});
                } else {
                    settingSpec(platformProductTypeId, obj);
                    table.render();
                }
            } else if (obj.event === 'syns') { // 同步到云端
                syns(data);
            }
        });

        //设置平台规格
        function settingSpec(platformProductTypeId, obj) {
            var data = obj.data;
            var windowId = admin.open({
                type: 1,
                area: '945px',
                offset: '165px',
                height: 465,
                title: '设置平台规格',
                content: $('#settingSpecForm').html(),
                success: function () {

                    //查询企业信息
                    /*var enterpriseInfo;
                    admin.req('enterprise/system/admin/system/getLoginInfo', {}, function (res) {
                        enterpriseInfo = res.data;
                    }, 'get', false);*/


                    //生成平台规格和规格值
                    //根据物料类型ID获取该类型下的规格
                    var subProductValueData;
                    admin.req('enterprisecab/productCab/admin/product/getProductSpecByProductTypeId', {productTypeId: platformProductTypeId}, function (res) {
                        subProductValueData = res.data;
                        createPloatformSpecValue(res.data);
                    }, 'get', false);

                    // 表单提交事件
                    $("#platformSpecSkuSetting").click(function () {
                        //var platformSkuCode = $("#synsPlatformSkuCode").val();
                        $("#platformSpecValueTb" + data.skuCode).html($("#platformProductSpecValueName").html());
                        $("#platformSpecValueIdTb" + data.skuCode).val($("#platformProductSpecValueId").val());
                        $("#platformSpecIdTb" + data.skuCode).val($("#platformProductSpecId").val());
                        layer.close(windowId);
                    });

                }
            })
        }
        function createEnterpriseProductAttr(data) {
            let html = '';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                //多选
                if (data[i].style == 'many') {
                    html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                    html += '<div class="layui-form-item">';
                    html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                    html += '<div class="layui-input-block">';

                    for (let j = 0; j < data[i].productAttributeValue.length; j++) {
                        var subData = data[i].productAttributeValue[j];
                        html += '<input lay-filter="enterpriseProductAttrValue' + data[i].id + '" type="checkbox" name  = "enterpriseProductAttrValue' + data[i].id + '"  value="' + subData.id + '" lay-skin="primary" title="' + subData.value + '" disabled>';
                    }
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                }
                //单选
                if (data[i].style == 'single') {
                    html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                    html += '<div class="layui-form-item">';
                    html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                    html += '<div class="layui-input-block">';
                    html += '<select lay-filter="enterpriseProductAttrValue' + data[i].id + '"  name="enterpriseProductAttrValue' + data[i].id + '" id="enterpriseProductAttrValue' + data[i].id + '" lay-verify="required" disabled>';
                    html += '<option value="">请选择属性</option>';
                    for (let j = 0; j < data[i].productAttributeValue.length; j++) {
                        var subData = data[i].productAttributeValue[j];
                        html += '<option value="' + subData.id + '">' + subData.value + '</option>';
                    }
                    html += "</select>";
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                }
                //文本
                if (data[i].style == 'text') {
                    html += '<div style="margin-top: 20px" name="attrValue' + data[i].name + '">';
                    html += '<div class="layui-form-item">';
                    html += '<label class="layui-form-label" style="padding-left: 0;text-align: left;">' + data[i].name + ':</label>';
                    html += '<div class="layui-input-block">';
                    html += '<input type="text" class="layui-input" lay--filter="enterpriseProductAttrValue' + data[i].id + '" name="enterpriseProductAttrValue' + data[i].id + '" id="enterpriseProductAttrValue' + data[i].id + '" lay-verify="required" disabled/>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                }
            }
            //console.log(html);
            $("[name='enterpriseProductAttrHtml']").html(html);
            form.render();

        }
        //同步数据到云端
        function syns(skuObj) {
            var id = skuObj.productId;
            var picture = $("#pictureSyns").val();
            var name = $("#platformName").val();
            var productCode = $("#platformProductCode").val();
            var productTypeId = $("#platformProductTypeId").val();
            var productCategoryId = $("input[name='platformProductCategoryId']").val();
            var platformProductCategoryExt = $("input[name='platformProductCategoryIdExt']").val();
            var brandCode = $("#platformBrandId").val();
            var unitCode = $("#platformUnitId").val();

            if (null == picture || "" == picture) {
                layer.msg("请上传商品图片", {icon: 2});
                return;
            }
            if (null == name || "" == name) {
                layer.msg("请输入商品名称", {icon: 2});
                return;
            }
            if (null == productTypeId || "" == productTypeId) {
                layer.msg("请选择商品类型", {icon: 2});
                return;
            }
            if (null == productCategoryId || "" == productCategoryId) {
                layer.msg("请选择商品分类", {icon: 2});
                return;
            }
            if (null == brandCode || "" == brandCode) {
                layer.msg("请选择品牌", {icon: 2});
                return;
            }
            if (null == unitCode || "" == unitCode) {
                layer.msg("请选择单位", {icon: 2});
                return;
            }

            //获取物料属性
            var attrArry = [];
            var productAttrData;
            admin.req('enterprisecab/cabProduct/admin/productAttribute/getProductAttrByProductTypeId', {productTypeId: productTypeId}, function (res) {
                productAttrData = res.data;
            }, 'get', false);
            for (var k = 0; k < productAttrData.length; k++) {
                var tempObj = productAttrData[k];
                //多选 获取值
                var subAttrArry = [];
                if (tempObj.style == 'many') {
                    $("input:checkbox[name='platformProductAttrValue" + tempObj.id + "']:checked").each(function (i) {
                        var subArrrObj = {
                            attrId: tempObj.id,
                            value: $(this).attr('title'),
                            valueId: $(this).val()
                        };
                        subAttrArry.push(subArrrObj);
                    });
                    if (subAttrArry.length > 0) {
                        var attrObj = {
                            attrId: tempObj.id,
                            attrName: tempObj.name,
                            productDetailAttributeValueForm: subAttrArry,
                            style: 0
                        };
                        attrArry.push(attrObj);
                    }
                }
                //单选 获取值
                if (tempObj.style == 'single') {
                    var selectVal = $("#platformProductAttrValue" + tempObj.id).val();
                    var selectName = $("#platformProductAttrValue" + tempObj.id).find("option:selected").text();

                    if (selectVal != '') {
                        var subArrrObj = {
                            attrId: tempObj.id,
                            value: selectName,
                            valueId: selectVal
                        };
                        subAttrArry.push(subArrrObj);
                    }
                    if (subAttrArry.length > 0) {
                        var attrObj = {
                            attrId: tempObj.id,
                            attrName: tempObj.name,
                            productDetailAttributeValueForm: subAttrArry,
                            style: 1
                        };
                        attrArry.push(attrObj);
                    }
                }
                //文本 获取值
                if (tempObj.style == 'text') {
                    var selectVal = $("#platformProductAttrValue" + tempObj.id).val();
                    if (selectVal != '') {
                        var attrObj = {
                            attrId: tempObj.id,
                            attrName: tempObj.name,
                            attrValue: selectVal,
                            style: 2
                        };
                        attrArry.push(attrObj);
                    }
                }
            }
            skuObj.platformSpecvalueName = $('#platformSpecValueTb' + skuObj.skuCode).html();
            skuObj.platformSpecvalueId = $('#platformSpecValueIdTb' + skuObj.skuCode).val();
            skuObj.platformSpecId = $('#platformSpecIdTb' + skuObj.skuCode).val();

            var productObj = {};
            productObj.id = id;
            productObj.picture = picture;
            productObj.name = name;
            productObj.productCode = productCode;
            productObj.productTypeId = productTypeId;
            productObj.productCategoryId = productCategoryId;
            productObj.productCategoryExtId = platformProductCategoryExt;
            //productObj.brandId = brandId;
            productObj.brandCode = brandCode;
            productObj.productDetailAttributeForm = attrArry;
            productObj.skuObj = skuObj;
            productObj.unitCode = unitCode;

            if (null == skuObj.platformSpecvalueId || "" == skuObj.platformSpecvalueId) {
                layer.msg("请设置平台商品规格", {icon: 2});
                return;
            }

            // console.log(subData);

            layer.confirm('确定要同步到云端吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                //layer.load(2);
                var json = JSON.stringify(productObj);
                admin.req('enterprise/product/admin/productSeriesWMS/syns', json, function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        var itemData = {};
                        itemData.picture = $("#enterpriseItemPic").val();
                        itemData.enterpriceCode = $("#enterpriseCode").val();
                        subData.forEach((emel, index) => {
                            if (emel.id == skuObj.id) {
                                emel.isSync = "yes";
                                emel.isSynsDes = "已同步";
                            }
                        })
                        createSkuTable(subData, itemData);
                        table.reload('platformProductSkuTable');
                        //layer.closeAll('page');
                    } else {
                        layer.msg(res.msg, {icon: 2});
                        return false;
                    }
                }, 'POST', true, 'application/json; charset=utf-8');
            });
        }

        //导入excel
        $('#uploaderInput').on("change", function (e) {
            layer.load(2);
            var formData = new FormData();
            var files = e.target.files;
            let that = $(this);
            formData.append("file", files[0]);
            formData.append("name", files[0].name);//这个地方可以传递多个参数
            $.ajax({
                url: config.base + 'enterprise/product/admin/productSeriesWMS/importExcel',
                data: formData,
                headers: {Authorization: 'Bearer ' + config.getToken()},
                type: "POST",
                processData: false,
                contentType: false,
                success: function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        // table.reload('humanResourcesTable');
                        layer.closeAll('page');
                        setTimeout(_ => {
                            location.reload()
                        }, 1000);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                    that.val('');
                }
            });

        })

        // 模板下载
        $('#fromLocalWarehouseBtnTemplate').click(function () {
            window.location.href = config.base + "enterprise/product/admin/productSeriesWMS/template";
        });

    });

</script>
